<template>
  <!-- 导航栏 -->

  <div class="container">
    <!-- 列表 -->
    <a-list
      item-layout="horizontal"
      :data-source="data.submitList"
      style="min-height: 350px"
    >
      <template #renderItem="{ item }">
        <a-list-item>
          <template #actions>
            <a v-if="item.stage == 0" @click="drop(item.request_id)"
              >撤回需求</a
            >
            <a
              v-else-if="item.stage == 1"
              @click="showerDrawer0(item.request_id)"
              >上传图片</a
            >
            <a v-else-if="item.stage == 2" @click="showerDrawer1(item)"
              >编辑题目</a
            >
            <a v-else-if="item.stage == 3">
              <a-tooltip placement="left">
                <template #title>
                  <span>这可能需要几天时间，请耐心等待</span>
                </template>
                正在标注
              </a-tooltip>
            </a>
            <a v-else @click="downLoad(item.request_id)">下载文件</a>
          </template>
          <a-list-item-meta>
            <template #description>
              <div v-if="item.description" style="display: inline-block">
                {{ item.description.substring(0, 50) }}
              </div>
              <div
                v-if="item.description.length >= 48"
                style="display: inline-block"
              >
                <text>...</text>
              </div>
            </template>
            <template #title>
              <a>{{ item.title }}</a>
            </template>
          </a-list-item-meta>
          <div>{{ option.Boolean[item.stage] }}</div>
        </a-list-item>
      </template>
    </a-list>

    <!-- 按钮 -->
    <a-button
      type="primary"
      @click="showDrawer"
      style="position: absolute; left: 38%"
    >
      <PlusOutlined />
      新的需求
    </a-button>
    <!-- 新建submit抽屉 -->
    <a-drawer
      title="新建需求"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <a-form :model="form" :rules="rules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="Title" name="title">
              <a-input v-model:value="form.title" placeholder="请输入标题" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="Question_content" name="question_content">
              <a-input
                v-model:value="form.question_content"
                placeholder="请填写您需要标注者回答的问题是什么"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Size" name="size">
              <a-input
                v-model:value="form.size"
                style="width: 100%"
                placeholder="您提出的需求中包含多少张需要标注的图片"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="期望的回收日期(最快一周)" name="deadLine">
              <a-date-picker
                format
                style="width: 100%"
                :get-popup-container="(trigger) => trigger.parentNode"
                :disabled-date="disabledDate"
                @change="onChangeTime"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Mode" name="mode">
              <a-select
                v-model:value="form.mode"
                placeholder="请选择回答的问题的题型"
              >
                <a-select-option value="选择题">选择题</a-select-option>
                <a-select-option value="填空题">填空题</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="Description" name="description">
              <a-textarea
                v-model:value="form.description"
                :rows="4"
                placeholder="请对您的需求进行一些详细的描述"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-button style="margin-right: 8px" @click="onClose">Cancel</a-button>
        <a-button type="primary" @click="onClose">Submit</a-button>
      </template>

      <a-button type="primary" @click="checkNull">提交</a-button>
    </a-drawer>
    <!-- 上传图片抽屉 -->
    <a-drawer
      title="上传图片"
      :width="720"
      :visible="visible0"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose0"
    >
      <section>
        <a-input
          type="file"
          webkitdirectory
          id="uploadFile"
          @change="handleChange"
          style=""
        />
        <div v-for="item in submit.listt" v-bind:key="item">
          {{ item.name }}
        </div>
        <a-button
          type="primary"
          @click="uploadPic(drawerId)"
          style="margin-top: 50px; margin-left: 280px"
          >提交</a-button
        >
      </section>

      <template #footer>
        <a-button style="margin-right: 8px" @click="onClose0">Cancel</a-button>
        <a-button type="primary" @click="onClose0">Submit</a-button>
      </template>
    </a-drawer>
    <!-- 编辑题目抽屉 -->
    <a-drawer
      title="编辑题目"
      :width="720"
      :visible="visible1"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose1"
    >
      <a-divider>修改题目及题目类型</a-divider>
      <a-form
        :model="changeObj"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-item label="需求内容">
          <a-input v-model:value="changeObj.question_content" />
        </a-form-item>

        <a-form-item label="需求类型">
          <a-radio-group v-model:value="changeObj.mode">
            <a-radio value="选择题">选择题</a-radio>
            <a-radio value="填空题">填空题</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <a-divider>设置选项</a-divider>
      <div v-if="changeObj.mode == '选择题'">
        <div
          v-for="item in options"
          :key="item.type"
          style="display: flex; flex-direction: column; justify-content: center"
        >
          <a-form
            :model="options"
            :label-col="{ span: 10 }"
            :wrapper-col="{ span: 16 }"
          >
            选项{{ item.type }}:
            <a-form-item>
              <a-input v-model:value="item.content" />
            </a-form-item>
          </a-form>
        </div>
        <div
          style="
            display: flex;
            flex-direction: row;
            justify-content: space-around;
          "
        >
          <a-button type="primary" @click="addItem"> 新增选项 </a-button>
          <a-button type="primary" @click="removeItem">删除选项</a-button>
        </div>
      </div>
      <div v-else><p>填空题不需要配置选项</p></div>
      <div style="display: flex; justify-content: space-around">
        <a-button type="primary" @click="setChange" style="margin-top: 50px"
          >提交修改</a-button
        >
      </div>
    </a-drawer>
  </div>
</template>
<script setup>
/////////////////////////////////////////////////////////////////
import { reactive, ref } from "vue";
import { get, post, getBlob, getLocalToken, tip } from "@/common";
import { PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
////////////////////////////////////////////////////////////////

const visible1 = ref(false);
const showerDrawer1 = (info) => {
  changeObj.request_id = info.request_id;
  changeObj.user_id = info.user_id;
  changeObj.question_content = info.question_content;
  changeObj.mode = info.mode;
  changeObject.request_id = info.request_id;
  changeObject.mode = info.mode;
  visible1.value = true;
};
const onClose1 = () => {
  visible1.value = false;
};

const addItem = () => {
  if (options.value.length <= 7) {
    var len = options.value.length;
    var typeS = optionsType.value[len];
    options.value.push({
      type: typeS,
      content: "",
    });
  } else {
    message.error("最多8个选项");
  }
};

const removeItem = () => {
  options.value.pop();
};

const changeObj = reactive({
  request_id: "",
  mode: "",
  question_content: "",
  user_id: "",
});

const posts = () => {
  post("/demander/setoption", changeObject).then((res) => {
    tip.success("设置选项成功！");
  });
};

const setChange = () => {
  //执行修改

  post("/demander/updatequestion", changeObj).then((res) => {
    changeObj.question_content = "";
    changeObj.mode = "";
    tip.success("编辑题目成功！");
  });
  if (changeObject.mode == "选择题") {
    for (var i = 0; i < options.value.length; i++) {
      changeObject.option_type = options.value[i].type;
      changeObject.option_content = options.value[i].content;
      posts();
      setTimeout(5000);
    }
  }
  visible1.value = false;
  getSubmit();
};

const changeObject = reactive({
  request_id: "",
  mode: "",
  option_content: "",
  option_type: "",
});

const options = ref([]);

const optionsType = ref(["A", "B", "C", "D", "E", "F", "G", "H"]);

/////////////////////////////////////////////////////////////////
const visible0 = ref(false);
const drawerId = ref(0);
const showerDrawer0 = (requestID) => {
  visible0.value = true;
  drawerId.value = requestID;
};
const onClose0 = () => {
  visible0.value = false;
};

const submit = reactive({
  listt: [],
  currentQuestion: {}, //当前需求信息
  currentFile: null, //当前图片文件
  currentImgUrl: null, //当前图片路径
});
const handleChange = () => {
  let files = document.getElementById("uploadFile").files; // FileList 伪数组对象
  submit.listt = files;
  for (let i = 0; i <= files.length - 1; i++) {
    let file = files[i]; // File 对象
    console.log(file);
  }
};

const uploadPic = (requestID) => {
  let files = document.getElementById("uploadFile").files; // FileList 伪数组对象

  const mydata = new FormData();

  for (let i = 0; i <= files.length - 1; i++) {
    mydata.append("files", files[i]);
    console.log("添加一个文件");
  }
  post("/demander/submit/pic?path=" + requestID, mydata).then((res) => {
    console.log(res);

    tip.success(res.message);
    getSubmit();
    visible0.value = false;
  });
};

////////////////////////////////////////////////////////////////
const option = {
  Boolean: {
    0: "待审核",
    1: "审核通过可上传图片",
    2: "图片上传成功可编辑题目",
    3: "已发布",
    4: "可回收",
  },
};

var data = reactive({
  submitList: [],
});

const token = getLocalToken();

const drop = (request_id) => {
  post("/demander/submit/delete/" + request_id).then((res) => {
    if (res.code == 200) {
      message.success("撤回需求成功，您可以重新提交您的需求");
      getSubmit();
    } else {
      message.error("撤回失败，审核可能已通过，请刷新页面重试");
    }
  });
};

const getSubmit = () => {
  get("/demander/submit/list", token).then((res) => {
    data.submitList = res.data;
    console.log(data.submitList);
  });
};
getSubmit();
////////////////////////////////////////////////////////////

const downLoad = (getfile) => {
  getBlob("/demander/toCsv/downLoad/" + getfile, {}, { loading: false }).then(
    (blob) => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      console.log(reader.result);
      reader.onload = (e) => {
        let a = document.createElement("a");
        a.download = getfile + ".csv";
        a.href = reader.result;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
    }
  );
};

////////////////////////////////////////////////////////////
const adate = new Date();

const disabledDate = (current) => {
  // Can not select days before today and today
  return current && current < dayjs().add(7, "day");
};
const checkNull = () => {
  console.log(form);
  if (form.title == "") {
    message.error("请输入标题");
  } else if (form.question_content == "") {
    message.error("请填写问题");
  } else if (form.size == "") {
    message.error("请填写图片的数目");
  } else if (isNaN(form.size)) {
    message.error("请在Size中填写数字");
  } else if (form.deadLine == "") {
    message.error("请选择截止日期");
  } else if (form.mode == "") {
    message.error("请选择题型");
  } else if (form.description == "") {
    message.error("请简单描述您的需求");
  } else {
    newSubmit();
  }
};

const newSubmit = () => {
  console.log(form);
  post("/demander/submit/insert", form).then((res) => {
    if (res.success) {
      getSubmit();
      visible.value = false;
    }
  });
};

const form = reactive({
  title: "",
  question_content: "",
  size: "",
  mode: "",
  deadLine: "",
  description: "",
});
const rules = {
  title: [
    {
      required: true,
      message: "Please enter this title",
    },
  ],
  question_content: [
    {
      required: true,
      message: "Please enter your question_content",
    },
  ],
  size: [
    {
      required: true,
      message: "please enter size",
    },
  ],
  mode: [
    {
      required: true,
      message: "Please choose the mode",
    },
  ],
  deadLine: [
    {
      required: true,
      message: "Please choose the deadLine",
    },
  ],
  description: [
    {
      required: true,
      message: "Please enter question description",
    },
  ],
};
const visible = ref(false);

const showDrawer = () => {
  visible.value = true;
};

const onClose = () => {
  visible.value = false;
};
const onChangeTime = (value, dateString) => {
  var a = dateString.split("-");
  var s = a.join("");
  var journalTime = a[0] + "-" + a[1] + "-" + a[2];
  form.deadLine = journalTime;
  console.log(journalTime);
  console.log(form);
};
</script>

<style>
.container {
  margin: 50px;
}
input {
  margin: 0.4rem 0;
  border: 1px solid white;
}
</style>